extern crate serial;

use std::time::Duration;
use std::thread;
use serial::prelude::*;
use std::io::{self, Write, Read};

fn main() {
    const SETTINGS: serial::PortSettings = serial::PortSettings {
        baud_rate: serial::Baud115200,
        char_size: serial::Bits8,
        parity: serial::ParityNone,
        stop_bits: serial::Stop1,
        flow_control: serial::FlowNone,
    };

    let mut port = serial::open("COM3").unwrap();
    port.configure(&SETTINGS).unwrap();
    port.set_timeout(Duration::from_millis(1000)).unwrap();
    let mut buf: Vec<u8> = (0..255).collect();

    loop {
        // 读取用户输入
        print!("请输入要发送的数据: ");
        io::stdout().flush().unwrap();

        let mut input = String::new();
        io::stdin().read_line(&mut input).expect("读取用户输入失败");

        // 发送数据到串口
        let data = input.trim().as_bytes();
        match port.write(data) {
            Ok(_) => println!("数据发送成功: {:?}", data),
            Err(e) => println!("发送数据失败: {}", e),
        }

        // 读取串口返回的数据
        if let Ok(n) = port.read(&mut buf[..]) {
            for i in 0..n {
                print!("{:02x }", buf[i]);
            }
            println!();
        }

        thread::sleep(Duration::from_millis(10));
    }
}